 package com.suozq.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 锁战强
 * @date 2022/04/07
 */
public class BlockServer {
    
    private static boolean RUNING = true;
    
    private static int PORT = 6666;
    
    public static class Dispatch implements Runnable{
        public static final AtomicInteger count = new AtomicInteger(0);
        
        private SocketChannel socketChannel;
       
        public Dispatch(SocketChannel socketChannel) {
            this.socketChannel = socketChannel;
        }
        
        @Override
        public void run() {
           count.incrementAndGet();
           ByteBuffer bb = ByteBuffer.allocate(1024);
           StringBuilder sb = new StringBuilder();
           try {
               while(socketChannel.read(bb)>-1) {
                   bb.flip();
                   sb.append(new String(bb.array()));
                   bb.clear();
               }
               System.out.println(Thread.currentThread().getName()+":"+count+":"+sb.toString());
               bb.put(("今天的第"+count+"次请求").getBytes());
               bb.flip();
               socketChannel.write(bb);
               socketChannel.close();
            } catch (IOException e) {
                 e.printStackTrace();
            }
        }
        
    }
    
    
    
    public static void main(String[] args) {
        System.out.println("服务启动于"+PORT);
        try(ServerSocketChannel server = ServerSocketChannel.open()){
            server.bind(new InetSocketAddress(PORT));
            while(RUNING&&!Thread.interrupted()) {
               // System.out.println("服务端处理第"+Dispatch.count+"个请求");
                SocketChannel socketChannel =  server.accept();
                new Thread(new Dispatch(socketChannel)).start();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
